package com.passion.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.passion.bean.OfflineAnalyseResult;
import com.passion.common.R;
import com.passion.service.OfflineAnalyseResultService;
import com.passion.service.OfflineAnalysisTemplateSqlTableService;

import com.passion.utils.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;


/**
 * @program offline-e-commerce-data-warehouse
 * @Description 离线分析服务
 * @Author limeihua
 * @Date 2024/09/28 19:14
 * @Version 1.0
 */
@RestController
@RequestMapping("/offline")
public class OfflineAnalyticController {
    @Autowired
    private OfflineAnalysisTemplateSqlTableService service;

    @Autowired
    private OfflineAnalyseResultService offlineAnalyseResultService;

    /**
     * 通用离线分析接口
     *
     * @param req
     * @return
     */
    @PostMapping("/universalAnalytic")
    public R offline(@RequestBody Map<String, Object> req) {
        String result = service.executeAnalysis(req);
        JSONArray resultArray = JSONArray.parseArray(result);
        return R.ok(resultArray);
    }

    /**
     * 手动触发执行所有离线分析任务
     *
     * @return]
     */
    @GetMapping("/executeAllSql")
    public R executeAllSql() {
        service.executeEverydayAnalysis();
        return R.ok();
    }

    /**
     * @param req 单值通用离线分析接口
     * @return
     */
    @PostMapping("/singleValueAnalyse")
    public R singleValue(@RequestBody Map<String, Object> req) {
        String date = (String) req.get("date");
        String key = (String) req.get("key");
        if (req.get("date") == null) {
            // 获取昨天的日期
            date = DateTimeUtil.timeStampToDate(System.currentTimeMillis() - 86400 * 1000);
        }
        OfflineAnalyseResult result = offlineAnalyseResultService.getOne(new QueryWrapper<OfflineAnalyseResult>().eq("sql_id", req.get("sqlID")).eq("analyse_time", date));
        if (result == null) {
            return R.error(-1, "没有查询到结果");
        }
        String analyseResult = result.getAnalyseResult();
        JSONArray jsonArray = JSONArray.parseArray(analyseResult);
        JSONObject jsonObject = (JSONObject) jsonArray.get(0);
        String value = jsonObject.getString(key);
        return R.ok(value);
    }
}
